package it.polimi.dei.SeCo.YAGO;

import java.sql.Connection;
import java.sql.DriverManager; 
import java.sql.SQLException;

/**
 * @author Simone Benefico
 */
public class DBAccess {
	private String server;
	private String dbName;
	private String user;
	private String password;
	private int port;
			
	/**
	 * Sets all the Calls variables to the values of the given parameters.
	 * @param srvName name or IP of the server
	 * @param dbName name of the database
	 * @param user username used to access connect to the db
	 * @param password password used to access connect to the db
	 * @param port open port of the server listening for db connections
	 */
	public DBAccess(String srvName, String dbName, String user, String password, int port){
		this.server = srvName;
		this.user = user;
		this.dbName = dbName;
		this.password = password;
		this.port = port;
	}

	/**
	 * Creates a Connection to specified db using the PostgreSQL JDBC Driver
	 * @return the created connection
	 */
	public Connection getConnection(){
		Connection con = null;
		String url = "jdbc:postgresql://"+server+":"+port+"/"+dbName;
		try {
			Class.forName("org.postgresql.Driver").newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			con = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			System.err.println ("Error message: " + e.getMessage ());
			System.err.println ("Error number: " + e.getErrorCode ());
			e.printStackTrace();
		}
		return con;
	}

	public void setServer(String server) {
		this.server = server;
	}

	public void setDbName(String dbName) {
		this.dbName = dbName;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setPort(int port) {
		this.port = port;
	}	

}
